package cn.faifai.framework.utils;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashUtils {

    public static String calculateHash(InputStream inputStream, String algorithm) throws NoSuchAlgorithmException, IOException {
        MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1){
            messageDigest.update(buffer, 0, bytesRead);
        }
        byte[] hashBytes = messageDigest.digest();
        StringBuilder hexStr = new StringBuilder();
        for (byte b : hashBytes){
            String hex = Integer.toHexString(b & 0xff);// 位与操作确保传入的值是原始的byte数据，详细看补码规则
            // 如果转换后的16位哈希值长度为1，为了统一格式方便处理，前面补位0，使得都是两位
            if (hex.length() == 1) hexStr.append('0');
            hexStr.append(hex);
        }
        return hexStr.toString();
    }
}
